package dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bean.Distance;
import bean.Intersection;
import bean.Point;
import bean.Road;
import bean.Segment;
import exception.DBException;

/**
 * 在容器启动时，实例化，加速查询
 * 
 * @author bluishoul@gmail.com
 * 
 */
public class StaticData extends HibernateDaoSupport {
	public static List<Distance> allDistance = null;
	public static List<Point> allPoints = null;
	public static List<Intersection> allIntersection = null;
	public static List<Road> allRoads = null;

	public StaticData() {
	}

	@SuppressWarnings("unchecked")
	public synchronized List<Distance> getAllDistance(int area)
			throws DBException {
		if (allDistance == null || allDistance.size() == 0) {
			allDistance = this.getHibernateTemplate().find("from Distance");
			for (Iterator<Distance> d = allDistance.iterator(); d.hasNext();) {
				if (d.next().getPoint1().getArea().getId() != area) {
					d.remove();
				}
			}
		}
		return allDistance;
	}

	@SuppressWarnings("unchecked")
	public synchronized List<Point> getAllPoints(int area) throws DBException {
		if (allPoints == null || allPoints.size() == 0) {
			allPoints = this.getHibernateTemplate().find("from Point");
			if (area != -1)
				for (Iterator<Point> p = allPoints.iterator(); p.hasNext();) {
					if (p.next().getArea().getId() != area) {
						p.remove();
					}
				}
		}
		//getAllSegment(area);
		return allPoints;
	}

	@SuppressWarnings("unchecked")
	public synchronized List<Intersection> getAllLights(int area)
			throws DBException {
		if (allIntersection == null || allIntersection.size() == 0) {
			allIntersection = this.getHibernateTemplate().find(
					"from Intersection");
			for (Iterator<Intersection> l = allIntersection.iterator(); l
					.hasNext();) {
				Intersection t = l.next();
				boolean out = false;
				for (int i = 0; i < 8 && !out; i++) {
					if (t.get(i)!=null && t.get(i).getArea().getId() != area) {
						l.remove();
						out = true;
					}
				}
			}
		}
		return allIntersection;
	}

	@SuppressWarnings("unchecked")
	public synchronized List<Road> getAllRoads(int area) throws DBException {
		if (allRoads == null || allRoads.size() == 0) {
			allRoads = this.getHibernateTemplate().find("from Road");
			for (Iterator<Road> r = allRoads.iterator(); r.hasNext();) {
				if (r.next().getPoint()[0].getArea().getId() != area) {
					r.remove();
				}
			}
		}
		return allRoads;
	}

}
